package com.zxd.interview.eightthread.threadobjectclasscommonmethod;

/**
 * 两个线程交替打印奇数和偶数
 *  两个线程，一个打印奇数，另一个打印偶数
 * 实现思路：
 * 1. 使用 synchronized
 * 2. 使用 wait/notify 但是需要注意使用同一个处理逻辑
 */
public class TwoThreadPrintNumber {


    private static int count;
    private static int count2 = 0;

    private static Object object = new Object();
    private static final Object lock = new Object();

    public static void main(String[] args) {
//        method1();
        method2();
    }

    /**
     * 第二种方法 notify/wait
     */
    private static void method2() {
        Runnable runnable = () -> {
            while (count2 <= 100) {
                synchronized (lock) {
                    System.out.println(Thread.currentThread().getName() + ": " +(count2++));
                    lock.notify();
                    if (count2 <= 100) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        Thread thread1 = new Thread(runnable);
        thread1.setName("偶数：");
        thread1.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread thread2 = new Thread(runnable);
        thread2.setName("奇数：");
        thread2.start();
    }

    /**
     * 第一种方法 , synchronized
     */
    private static void method1() {
        new Thread(new PrintOddNumber()).start();
        new Thread(new PrintEvenNumber()).start();
    }

    /**
     * 奇数打印线程
     */
    static class PrintOddNumber implements Runnable {


        @Override
        public void run() {
            while (count < 100) {
                synchronized (object) {
//                    if (count % 2 != 0) {
                    // 更为高效的判断
                    if ((count & 1) != 1) {
                        System.out.println(Thread.currentThread() + " 奇数 " + count++);
                    }
                }
            }
        }
    }

    /**
     * 偶数打印线程
     */
    static class PrintEvenNumber implements Runnable {

        @Override
        public void run() {
            while (count < 100) {
                synchronized (object) {
//                    if (count % 2 == 0) {
                    if ((count & 1) == 1) {
                        System.out.println(Thread.currentThread() + " 偶数 " + count++);

                    }
                }
            }
        }
    }
}
